#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "calc.h"
#define MAXOP 100



int main() {
    //printf("%15.14f",atof("-123.45e-6"));

    int type, i, var=0;
    double op1,op2,v;
    char s[MAXOP];
    double variable[26];

    for (i = 0; i < 26; ++i) {
        variable[i] = 0.0;
    }

    while ((type = getop(s)) != EOF){
        switch (type) {
            case NUMBER:
                push(atof(s));
                break;
            case NAME:
                mathfnc(s);
                break;
            case '+':
                push(pop() + pop());
                break;
            case '*':
                push(pop() * pop());
                break;
            case '-':
                op2 = pop();
                push(pop() - op2);
                break;
            case '/':
                op2 = pop();
                if(op2 != 0.0)
                    push(pop() / op2);
                else
                    printf("error : zero divisor\n");
                break;
            case '%':
                op2 = pop();
                if(op2 != 0.0)
                    push(fmod(pop(), op2));
                else
                    printf("error : zero divisor\n");
                break;
            case '=':
                pop();
                if (var >= 'A' && var <= 'Z')
                    variable[var-'A'] = pop();
                else
                    printf("error: no variable name\n");
                break;
            case '?': //打印栈顶元素
                op2 = pop();
                printf("top ele is: %f \n", op2);
                push(op2);
                break;
            case 'd': //复制栈顶元素
                op2 = pop();
                push(op2);
                push(op2);
                break;
            case 's': //交换栈顶元素的值
                op1 = pop();
                op2 = pop();
                push(op1);
                push(op2);
                break;
            case 'c': //清空栈
                clear();
                break;
            case '\n':
                v = pop();
                printf("  \t%g\n ", v);
                break;
            default:
                if (type >= 'A' && type <= 'Z')
                    push(variable[type - 'A']);
                else if (type == 'v')
                    push(v);
                else
                    printf("error: unknown command %s\n", s);
                break;
        }
        var = type;
    }
    return 0;
}